<template>
  <div class="main-table-content">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70">
      <el-form-item label="课程编号" prop="kcNumber" label-width="80">
        <el-input v-model="searchForm.kcNumber" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="课程名称" prop="kcName" label-width="80">
        <el-input v-model="searchForm.kcName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item v-if="!option.isJs" label="教师名称" prop="jsName" label-width="80">
        <el-input v-model="searchForm.jsName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item v-if="!option.isJs" label="教师编号" prop="jsNumber" label-width="80">
        <el-input v-model="searchForm.jsNumber" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item v-if="!option.isBm" label="开课部门" prop="bmName" label-width="80">
        <el-input v-model="searchForm.bmName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="学年学期" prop="name" label-width="80">
        <el-input v-model="searchForm.name" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12" v-if="option.isJw || option.isBm">
      <el-button plain size="small" icon="Setting" @click="openZipManage">压缩包管理</el-button>
      <el-button type="primary" plain size="small" icon="Files" @click="createZipBatch">批量生成压缩包</el-button>
    </div>

    <!--按钮组-->
    <!--    <div class="fx mgb12">-->
    <!--      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>-->
    <!--    </div>-->

    <!--表格-->
    <el-table border highlight-current-row row-key="number" v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">

      <el-table-column type="selection" width="55"/>
      <el-table-column label="课程编号" prop="kcNumber" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="课程名称" prop="kcName" :show-overflow-tooltip="true" min-width="150"></el-table-column>
      <el-table-column label="教师名称" prop="jsName" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="教师编号" prop="jsNumber" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="开课部门" prop="bmName" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="学年学期" prop="name" :show-overflow-tooltip="true"></el-table-column>

      <el-table-column label="操作" align="center" fixed="right" :min-width="option.isJs?120:120">
        <template #default="scope">
          <el-button link type="primary" icon="UploadFilled" @click="setFileData(scope.row,scope.$index)">
            上传资料
          </el-button>
          <el-button link type="primary" icon="Edit" @click="openFile(scope.row)" style="margin-left: 10px">
            资料管理
          </el-button>

          <!--            <el-button v-if="option.isBm || option.isJw" link type="primary" icon="Files"-->
          <!--                       @click="createZip(scope.row)" style="margin-left: 10px">-->
          <!--              生成压缩包-->
          <!--            </el-button>-->

        </template>

      </el-table-column>

    </el-table>

    <!--分页-->
    <div class="fxEnd">
      <el-pagination
          class="mgt8"
          small
          background
          :total="option.totalRow"
          :page-sizes="option.pageSizes"
          v-model:current-page="searchForm.pageNumber"
          v-model:page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchData"
          @current-change="searchData"
      />
    </div>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="80%" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>
      <fileList
          :cj-number="option.cjNumber"
          :client="option.client"
          :is-jw="option.isJw"
          :is-bm="option.isBm"
          :is-js="option.isJs"
          :kcNumber="option.kcNumber"
          :jsNumber="option.jsNumber">
      </fileList>
    </el-dialog>


    <!--Dialog-->
    <el-dialog :title="option.dialogTitleZip" v-model="option.openDialogZip" width="80%" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>
      <zip-file-list
          :client="option.client"
          :is-jw="option.isJw"
          :is-bm="option.isBm"
          :is-js="option.isJs">
      </zip-file-list>
    </el-dialog>

    <!--Dialog-->
    <el-dialog title="上传文件" v-model="option.openDialogFile" width="80%" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>
      <el-upload drag
                 class="upload-demo"
                 action=""
                 ref="upload"
                 :show-file-list="true"
                 :data="fileData"
                 :on-success="uploadSuccess"
                 :on-error="uploadError"
                 :on-progress="uploadProgress"
                 :http-request="uploadHttp"

      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">
          将文件拖放到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
          </div>
        </template>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {updateMtRoom} from "@/api/mt";
import $modal from "@/common/utils/modal";
import {closeLoading, copyNew, showLoading, trimStr} from "@/common/utils/kit";
import {asDict} from "@/api/common";
import {dateToStr} from "@/common/utils/date";
import {
  bmCreateJsZip,
  bmDownloadZip,
  jwCreateJsZip,
  jwDownloadZip,
  selectBmTeacherCourse,
  selectJsTeacherCourse,
  selectJwTeacherCourse
} from "@/api/jldz";
import fileList from "@/view/jldz/fileList.vue";
import {getAccessToken} from "@/common/utils/cache";
import router from "@/common/router";
import {useRoute} from "vue-router";
import useUserStore from "../../common/store/userStore";
import ZipFileList from "@/view/jldz/zipFileList.vue";
import {ElMessageBox} from "element-plus";
import $event from "@/common/utils/event";
import axios from "axios";
//   let time = Math.ceil(((uploadFile.size * 1) / (1024 * 1024)))
//   let endTime = new Date().getTime() + (time * 1000) + (10 * 1000);
//   let nowTime = new Date().getTime();
//   let allTime = endTime - nowTime
//   console.log(" endTime ", endTime)
//   console.log(" endTime ", nowTime)
//   console.log(" endTime - nowTime ", allTime)
//   let addTime = 0;
//   setInterval(() => {
//     addTime += 500;
//     if (addTime >= allTime) addTime = allTime - 500;
//     console.log(" addTime ", addTime)
//     console.log(" allTime ", allTime)
//     console.log(" (addTime / allTime)*100 ", (addTime / allTime) * 100)
//     option.value.fileSaveProgress = Math.floor((addTime / allTime) * 100);
//   }, 500)
//文件：上传参数
const fileData = ref({});

//文件：设置上传参数
function setFileData(row, $index) {
  if (option.value.isJs) {
    //活动编号
    fileData.value.cjNumber = row.number
    //教师任务0；部门任务1；非任务2；
    fileData.value.taskType = '2'
  }
  // // 指定当前打开的上文组件Ref
  fileData.value.$fileRefIndex = $index
  option.value.openDialogFile = true;
}

//文件：状态变动
function uploadHttp(options) {
  console.log(" uploadHttp ", options);
  console.log(" uploadHttp .options .file ", options.file);

  const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
  const chunk = blobSlice.call(options.file, 0, 100);
  console.log(chunk)

  // 创建FormData上传
  let formData = new FormData();
  formData.enctype = "multipart/form-data";
  formData.append('file', options.file)
  formData.append("aaaa", "aaaaa");
  formData.append("cjNumber", fileData.value.cjNumber);
  formData.append("taskType", fileData.value.taskType);

  let header = {
    "Content-Type": "multipart/form-data",
    token: getAccessToken()
  }

  axios({
    method: 'post',
    headers: header,
    url: option.value.uploadUrl,//自定义上传url
    data: formData,
    onUploadProgress: (progressEvent) => {
      let percent = (progressEvent.loaded / progressEvent.total * 100) | 0
      console.log("onUploadProgress-->", percent)
    }
  })

}

//文件：状态变动
function uploadChange(file, files) {
  if (file && file.status === 'ready') {
    showLoading("正在上传文件，请耐心等待...")
    console.log("开始上传文件  file ----->", JSON.stringify(file))
    console.log("开始上传文件  fileData ----->", JSON.stringify(fileData.value))
    proxy.$refs["uploadRef" + fileData.value.$fileRefIndex].submit()
  }
}

//文件：上传之前拦截
function uploadBefore(rawFile) {
  console.log("uploadBefore  rawFile  ", rawFile)
}

//文件：上传进度
function uploadProgress(evt, uploadFile, uploadFiles) {
  console.log("uploadProgress  evt  uploadFile  uploadFiles", evt, uploadFile, uploadFiles)
}

//文件：上传成功
function uploadSuccess(res, file, files) {
  closeLoading()
  // console.log("uploadSuccess  res  file  files", res, file, files)
  if (res.success) {
    $modal.success("上传成功");
  } else {
    $modal.warning("上传失败" + res.message);
  }
}

//文件：上传失败
function uploadError(res, file, files) {
  closeLoading()
  // console.log("uploadError  res  file  files", res, file, files)
  $modal.warning("失败");
}

const {proxy} = getCurrentInstance();

const {enu_room_status} = asDict("enu_room_status");

const route = useRoute();
const routeParam = useRoute().query;

let optionKey = {
  loading: false,
  openDialog: false,
  dialogType: "",
  dialogTitle: "",
  openDialogZip: false,
  openDialogFile: false,
  dialogTitleZip: "",
  dialogTypeZip: "",
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [50, 100, 500, 1000, 2000, 5000],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
  kcNumber: '',
  jsNumber: '',
  client: '',//当前菜单
  isJw: false,//是否是教务处
  isBm: false,//是否是部门
  isJs: false,//是否是教师
  uploadUrl: import.meta.env.VITE_UPLOAD_URL + '/manage/jldz/uploadFile'
}

let searchKey = {
  pageNumber: 1,
  pageSize: 100,
  kcNumber: '',
  kcName: '',
  bmName: '',
  jsName: '',
  jsNumber: '',
  name: '',
}
let formKey = {
  id: "",
  inPassword: "",//入会密码
  isBeforeIn: "",//是否允许主持人不在时进入会议
  inType: "",//入会类型
  isInMute: "",//入会后是否自动静音
  closeSettingTime: "",//会议结束时间
}
const formRules = ref({
  isBeforeIn: [{required: true, message: "不能为空", trigger: "blur"}],
  inType: [{required: true, message: "不能为空", trigger: "blur"}],
  isInMute: [{required: true, message: "不能为空", trigger: "blur"}],
  closeSettingTime: [{required: true, message: "不能为空", trigger: "blur"}],
});

const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
  searchData()
}

//页面加载完成回调
onMounted(() => {
  option.value.client = routeParam.client
  option.value.isJw = routeParam.client === 'jwBmTask' || routeParam.client === 'jwTeacherTask' || routeParam.client === 'jwTeacherRes'
  option.value.isBm = routeParam.client === 'bmBmTask' || routeParam.client === 'bmTeacherRes'
  option.value.isJs = routeParam.client === 'teacherRes' || routeParam.client === 'teacherTask'

  let isOk = checkRouteParam();

  if (isOk) {
    searchData()
  }
})

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.number);
  option.value.selectNames = rows.map(item => item.kcName);
}

//搜索数据
function searchData() {
  option.value.loading = true;
  console.log("  searchForm.value ", searchForm.value)
  if (option.value.isJs) {
    selectJsTeacherCourse(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }
  if (option.value.isBm) {
    selectBmTeacherCourse(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }
  if (option.value.isJw) {
    selectJwTeacherCourse(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }

}

function searchReturnRes(res) {
  let {totalRow, records, pageNumber, pageSize} = res.data;
  option.value.loading = false;
  option.value.totalRow = totalRow * 1
  option.value.tableData = records
  searchForm.value.pageNumber = pageNumber * 1
  searchForm.value.pageSize = pageSize * 1
}

function openFile(row) {
  option.value.kcNumber = row.kcNumber
  option.value.jsNumber = row.jsNumber
  //console.log(row)
  let dJsName = row.jsName ? "-" + row.jsName : ''
  let dKcName = row.kcName ? "-" + row.kcName : ''
  option.value.dialogTitle = "资料管理" + dJsName + dKcName;
  option.value.openDialog = true;
  option.value.dialogType = "edit";
  option.value.cjNumber = row.number;
  formData.value = copyNew(row);
}

//
function createZip(row) {
  alert("压缩包正在生成中....。生成完毕后，在 “压缩包管理” 中查看。")
}

//打开管理页面
function openZipManage(row) {
  option.value.dialogTitleZip = "压缩包管理";
  option.value.openDialogZip = true;
  option.value.dialogTypeZip = "zip";
}

//批量生成压缩包
function createZipBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  ElMessageBox.prompt("如有需要，请自行修改输入框内的压缩包名称，无要求默认即可。", "批量生成压缩包", {
    inputPlaceholder: '请输入压缩包名称',
    inputValue: "课程资料-" + dateToStr(new Date(), "yyyyMMdd-HHmmss"),
    confirmButtonText: '立即生成',
    cancelButtonText: '取消',
    type: "warning",
  }).then(({value}) => {
    let zipName = trimStr(value)
    if (zipName.length === 0) {
      $modal.warning("压缩包名称不能为空");
      return;
    }

    showLoading("正在生成数据，请稍候...")

    let param = {
      zipName: zipName,
      cjNumbers: option.value.selectIds.join(","),
    }

    // 部门生成
    if (option.value.isBm) {
      bmCreateJsZip(param).then((res) => {
        closeLoading();
        if (res.success) {
          openToManage()
          $event.emit("searchMsg", {})
        }
      })
    }

    //教务处生成
    if (option.value.isJw) {
      jwCreateJsZip(param).then((res) => {
        closeLoading();
        if (res.success) {
          openToManage()
          $event.emit("searchMsg", {})
        }
      })
    }

  }).catch((c) => {
    $modal.cancel();
  })

}

//打包成功，提示前往管理页面
function openToManage() {
  return ElMessageBox.confirm("压缩包正在生成中。 点击“压缩包管理”按钮，前往查看压缩包生成状态。", "系统提示", {
    confirmButtonText: '压缩包管理',
    cancelButtonText: '关闭',
    type: "success",
  }).then((res) => {
    openZipManage()
  }).catch((c) => {
  })
}

//
function downloadBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  showLoading("正在下载数据，请稍候...")

  //console.log(ids)
  let content = `正在执行批量下载操作，下载中途不能切换页面，是否继续执行？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let param = {
          zipName: '批量下载压缩包.zip',
          cjNumbers: option.value.selectIds.join(","),
          type: '2'
        }

        if (option.value.isBm) {
          param.zipName = useUserStore().userInfo.nickName + '.zip'
          bmDownloadZip(param).then((data) => {
            saveAs(new Blob([data]), param.zipName);
            closeLoading();
          })
        }

        if (option.value.isJw) {
          jwDownloadZip(param).then((data) => {
            param.zipName = '教师课程资料.zip'
            saveAs(new Blob([data]), param.zipName);
            closeLoading();
          })
        }

      }).catch(() => {
        $modal.cancel()
        closeLoading()
      }
  );

}

function submitEdit() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      formData.value.closeSettingTime = dateToStr(formData.value.closeSettingTime)
      // formData.value.closeSettingTime = new Date(formData.value.closeSettingTime).getTime();
      //closeSettingTime 转成时间戳
      updateMtRoom(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function checkRouteParam() {
  console.log(route)
  console.log(routeParam)
  let isOk = (routeParam.type && routeParam.client) && ('/' + routeParam.client === route.path)

  //额外检查(teacherRes，必须等于99)
  if (route.path == '/teacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(bmTeacherRes，必须等于99)
  if (route.path == '/bmTeacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(jwTeacherRes，必须等于99)
  if (route.path == '/jwTeacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(bmBmTask，必须等于1)
  if (route.path == '/teacherTask' && routeParam.type != '0') isOk = false;

  //额外检查(bmBmTask，必须等于1)
  if (route.path == '/bmBmTask' && routeParam.type != '1') isOk = false;

  //额外检查(jwBmTask，必须等于1)
  if (route.path == '/jwBmTask' && routeParam.type != '1') isOk = false;

  //额外检查(jwTeacherTask，必须等于0)
  if (route.path == '/jwTeacherTask' && routeParam.type != '0') isOk = false;


  if (!isOk) {
    $modal.error("您访问的地址不完整，请 点击【菜单/选项卡】进入页面。正在跳转至首页....");
    setTimeout(() => {
      router.push("/index").then(() => {
        // window.location.reload()
      })
    }, 2000)
  }
  return isOk;
}

</script>

<style scoped lang="less">

</style>